package com.smarttiger.zero.admin.service;

import com.alibaba.fastjson.JSON;
import com.smarttiger.zero.admin.dao.MessageDao;
import com.smarttiger.zero.admin.dao.SubscribeDao;
import com.smarttiger.zero.admin.entity.MessageModel;
import com.smarttiger.zero.admin.entity.SubscribeModel;
import com.smarttiger.zero.admin.util.Constant;
import com.smarttiger.zero.admin.util.Message;
import com.smarttiger.zero.admin.util.ParamNames;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class MessageService extends BaseService<MessageModel> {
    @Autowired
    MessageDao dao;

    @Autowired
    SubscribeDao subscribeDao;

    @PostConstruct
    public void initMethod() {
        super.setDao(dao);
    }

    @ParamNames("name,page")
    public Message getMessage(String name,String page) {
        Message message = new Message();
        Pageable pageable = PageRequest.of(Integer.valueOf(page).intValue(), Constant.PAGESIZE, Sort.by(Sort.Direction.DESC,"createDate"));
        Page<MessageModel> all = dao.findAll(new Specification<MessageModel>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<MessageModel> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (!StringUtils.isEmpty(name)) {
                    predicates.add(criteriaBuilder.like(root.get("name"), name + "%"));
                }
                criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createDate")));
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        },pageable);
        long totalElements = all.getTotalElements();
        message.setData(all.getContent());
        message.setTotal((int)totalElements);
        return message;
    }

    @ParamNames("name,userId,page")
    public Message getMessageByUser(String name,String userId,String page) {
        Message message = new Message();
        Pageable pageable = PageRequest.of(Integer.valueOf(page).intValue(), Constant.PAGESIZE, Sort.by(Sort.Direction.DESC,"createDate"));
        Page<MessageModel> all = dao.findAll(new Specification<MessageModel>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<MessageModel> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (!StringUtils.isEmpty(name)) {
                    predicates.add(criteriaBuilder.like(root.get("name"), name + "%"));
                }
                criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createDate")));
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        },pageable);
        long totalElements = all.getTotalElements();
        List<MessageModel> messageModels = all.getContent();
        List<HashMap> list = new ArrayList<>();
        for (MessageModel messageModel : messageModels) {
            List<SubscribeModel> ss = subscribeDao.findByUsersIdAndMessageId(userId, messageModel.getId());
            HashMap hashMap = JSON.parseObject(JSON.toJSONString(messageModel), HashMap.class);
            if(ss.size()>0){
                hashMap.put("isSub",ss.get(0).getId());
            }else {
                hashMap.put("isSub","");
            }
            list.add(hashMap);
        }
        message.setData(list);
        message.setTotal((int)totalElements);
        return message;
    }

    @Transactional
    @Override
    public void delete(String id) {
        super.delete(id);
        subscribeDao.deleteByMessageId(id);
    }
}
